package com.example.taobaounion.presenter.impl;

import android.annotation.SuppressLint;

import androidx.annotation.NonNull;

import com.example.taobaounion.model.Api;
import com.example.taobaounion.model.domain.HomePagerContent;
import com.example.taobaounion.presenter.ICategoryPagerPresenter;
import com.example.taobaounion.utils.LogUtils;
import com.example.taobaounion.utils.RetrofitUtils;
import com.example.taobaounion.utils.UrlUtils;
import com.example.taobaounion.view.callback.ICategoryPagerCallback;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class CategoryPagerPresenter implements ICategoryPagerPresenter {

    private static final String TAG = "CategoryPagerPresenter";

    @SuppressLint("UseSparseArrays")
    private Map<Integer, Integer> pagesInfo = new HashMap<>();
    private final static Integer DEFAULT_PAGE = 1;

    private List<ICategoryPagerCallback> mCallbacks = new ArrayList<>();
    private Integer mCurrentPage;


    @Override
    public void getContentByCategoryId(int categoryId) {
        // 根据分类id去加载内容
        for (ICategoryPagerCallback callback : mCallbacks) {
            callback.onLoading(categoryId);
        }

        Integer targetPage = pagesInfo.get(categoryId);

        if (targetPage == null) {
            targetPage = DEFAULT_PAGE;
            pagesInfo.put(categoryId, targetPage);
        }

        Call<HomePagerContent> task = createTask(categoryId, targetPage);

        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(@NonNull Call<HomePagerContent> call, @NonNull Response<HomePagerContent> response) {
                int code = response.code();
                LogUtils.d(TAG, "result code -->" + code);

                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent pagerContent = response.body();

//                    LogUtils.d(TAG, "pageContent --->" + pagerContent);

                    assert pagerContent != null;
                    handleHomePageContentResult(pagerContent, categoryId);
                } else {
                    handleNetworkError(categoryId);
                }
            }

            @Override
            public void onFailure(@NonNull Call<HomePagerContent> call, @NonNull Throwable t) {
                LogUtils.d(TAG, "result code -->" + t.toString());
                handleNetworkError(categoryId);
            }

            private void handleNetworkError(int categoryId) {
                for (ICategoryPagerCallback callback : mCallbacks) {
                    callback.onNetworkError(categoryId);
                }
            }

            /**
             * 通知 view layer 跟新数据
             *
             * @param pagerContent data
             * @param categoryId   分类Id
             */
            private void handleHomePageContentResult(HomePagerContent pagerContent, int categoryId) {
                List<HomePagerContent.DataBean> data = pagerContent.getData();

                for (ICategoryPagerCallback callback : mCallbacks) {
                    if (pagerContent.getData().size() == 0) {
                        callback.onEmpty(categoryId);
                    } else {
                        List<HomePagerContent.DataBean> looperData = data.subList(data.size() - 5, data.size());


                        // 拿一些商品数据做轮播图
                        callback.onLooperListLoaded(looperData);
                        callback.onContentLoaded(data, categoryId);
                    }
                }
            }
        });
    }

    private Call<HomePagerContent> createTask(int categoryId, Integer targetPage) {
        Retrofit retrofit = RetrofitUtils.getInstance().getRetrofit();

        Api api = retrofit.create(Api.class);
        return api.getHomePagerContent(UrlUtils.createHomePagerUrl(categoryId, targetPage));
    }


    @Override
    public void loadMore(int categoryId) {
        // load more
        // 1.拿到当前页码
        mCurrentPage = pagesInfo.get(categoryId);
        if (mCurrentPage == null) {
            mCurrentPage = 1;
        }
        // 2.页码++
        mCurrentPage++;
        // 3.加载数据
        Call<HomePagerContent> task = createTask(categoryId, mCurrentPage);
        // 4.处理数据
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(@NonNull Call<HomePagerContent> call, @NonNull Response<HomePagerContent> response) {
                int code = response.code();

                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent result = response.body();

                    handleLoaderResult(result, categoryId);
                } else {
                    handleLoaderMoreError(categoryId);
                }
            }

            @Override
            public void onFailure(@NonNull Call<HomePagerContent> call, @NonNull Throwable t) {
                LogUtils.d(TAG, t.toString());
                handleLoaderMoreError(categoryId);
            }
        });
    }

    private void handleLoaderResult(HomePagerContent result, int categoryId) {

        if (result == null || result.getData().size() == 0) {
            for (ICategoryPagerCallback callback : mCallbacks) {
                callback.onLoadMoreEmpty(categoryId);
            }

            return;
        }

        for (ICategoryPagerCallback callback : mCallbacks) {
            callback.onLoadMoreLoaded(result.getData(), categoryId);
        }
    }

    private void handleLoaderMoreError(int categoryId) {
        mCurrentPage--;
        pagesInfo.put(categoryId, mCurrentPage);
        for (ICategoryPagerCallback callback : mCallbacks) {
            callback.onLoadMoreError(categoryId);
        }
    }

    @Override
    public void reload(int categoryId) {

    }


    @Override
    public void registerViewCallback(ICategoryPagerCallback callback) {
        if (!mCallbacks.contains(callback)) {
            mCallbacks.add(callback);
        }
    }

    @Override
    public void unRegisterViewCallback(ICategoryPagerCallback callback) {
        mCallbacks.remove(callback);
    }
}

